<template>
  <div class='tab-box'>
    <div class='flex top-box'>
      <div style="display: flex;justify-content: center;align-items: center;">
        <div style="font-size: 16px;font-weight: 600;color: #333;padding-left: 10px;">重要知识点：</div>
        <input class='inputStyle' type="file" @change="handleFileUpload" />
      </div>
      <el-button
        type="primary"
        size='small'
        :disabled="excelData.length == 0"
        @click="uploadData"
      >提交</el-button>
    </div>
    <div v-if="excelDataBak || col.length > 0">
      <el-table
        :data="excelData"
        border
        style="width: 100%"
        size="mini"
        :span-method="objectSpanMethod"
        :header-cell-style="{ textAlign: 'center', backgroundColor: '#F5F7FA' }"
      >
        <el-table-column
          v-for="(item, index) in col"
          :key="index"
          :prop="item.headValue"
          :label="item.headName"
          minWidth="180"
        >
          <template slot-scope="scope">
            {{ scope.row[item.headValue] }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="delItem(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
export default {
  props: {
    examinationId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      excelDataBak: null,
      colFields: [],
      excelData: [],
      col: [],
      pageIndex: 1,
      pageSize: 100000
    }
  },
  methods: {
    updateData () {
      setTimeout(() => {
        if (!this.examinationId) {
          this.excelDataBak = null
          this.colFields = []
          this.excelData = []
        } else {
          this.getData()
        }
      }, 150)
    },
    getData () {
      console.log(this.examinationId, 2222)

      this.$http({
        url: '/study/exampoints/list',
        method: 'get',
        params: {
          examinationId: this.examinationId,
          page: this.pageIndex,
          limit: this.pageSize
        }
      }).then(({ data }) => {
        if (data.code === 0) {
          if (data.page.records.length === 0) {
            this.col = []
            this.excelData = []
          } else {
            this.excelData = []
            this.col = [
              {
                headName: '标题',
                headValue: `head0`
              },
              {
                headName: '内容',
                headValue: `head1`
              }
            ]
            data.page.records.map((val, index) => {
              this.excelData.push({
                head0: val.title,
                head1: val.content
              })
            })
            setTimeout(() => {
              console.log(this.col)
              console.log(this.excelData)
            }, 100)
          }
        }
      })
    },
    uploadData () {
      if (!this.examinationId) {
        this.$message.warning('请先创建习题')
        return
      }
      let params = []
      this.excelData.map((val, index) => {
        params.push({
          title: val.head0,
          content: val.head1,
          ordersn: index + 1,
          examinationId: this.examinationId
        })
      })
      // 需要先清空再上传
      this.$http({
        url: `/study/exampoints/deleteByExaminationId?examinationId=${this.examinationId}`,
        method: 'post',
        data: {
          examinationId: this.examinationId
        }
      }).then(({ data }) => {
        console.log(data)
        this.save(params)
      })
    },
    save (params) {
      this.$http({
        url: '/study/exampoints/saveList',
        method: 'post',
        data: params
      }).then(({ data }) => {
        console.log(data)
        this.$message.success('保存成功～')
      })
    },
    delItem (val) {
      let arr = JSON.parse(JSON.stringify(this.excelData))
      this.excelData = arr.filter(item => JSON.stringify(item) !== JSON.stringify(val))
    },
    handleFileUpload (event) {
      const file = event.target.files[0]
      const reader = new FileReader()
      reader.onload = e => {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        this.excelDataBak = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        // console.log("this.excelDataBak", this.excelDataBak);
        this.col = []
        this.colFields = []
        this.excelData = []

        for (let q = 0; q < this.excelDataBak.length; q++) {
          if (this.excelDataBak[q][0] === undefined) {
            this.excelDataBak[q][0] = this.excelDataBak[q - 1][0]
          }
        }
        this.excelDataBak[0].map((item, index) => {
          this.col.push({
            headName: item,
            headValue: `head${index}`
          })
          this.colFields.push(`head${index}`)
        })
        for (let i = 1; i < this.excelDataBak.length; i++) {
          let obj = {}
          for (let k = 0; k < this.excelDataBak[i].length; k++) {
            obj[`head${k}`] = this.excelDataBak[i][k]
          }
          this.excelData.push(obj)
        }
      }
      reader.readAsArrayBuffer(file)
    },

    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        // 获取当前单元格的值
        const currentValue = row[column.property]
        // 获取上一行相同列的值
        const preRow = this.excelData[rowIndex - 1]
        const preValue = preRow ? preRow[column.property] : null
        // 如果当前值和上一行的值相同，则将当前单元格隐藏
        if (currentValue === preValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          // 否则计算当前单元格应该跨越多少行
          let rowspan = 1
          for (let i = rowIndex + 1; i < this.excelData.length; i++) {
            const nextRow = this.excelData[i]
            const nextValue = nextRow[column.property]
            if (nextValue === currentValue) {
              rowspan++
            } else {
              break
            }
          }
          return { rowspan, colspan: 1 }
        }
      }
    }
  }
}
</script>
<style lang="scss">
.tab-box {
  .top-box {
    justify-content: space-between;
    .inputStyle {
      height: 32px;
      line-height: 26px;
    }
  }
}
</style>